///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
#include <Model/VertexIndexBuffer.h>

//-----------------------------------------------------------------------------

VertexIndexBuffer::VertexIndexBuffer()
{
	m_noComponents = 0;
	m_dataType = eIDT_U_BYTE;
	m_dataPtr = NULL;
}

//-----------------------------------------------------------------------------

VertexIndexBuffer::~VertexIndexBuffer()
{
	ReleaseData();
}

//-----------------------------------------------------------------------------

void	VertexIndexBuffer::InitData(eIndexDataType	dataType,	u32	noComponents)
{
	if( m_dataPtr )
	{
		ReleaseData();
	}

	ASSERT( noComponents > 0 );
	m_noComponents = noComponents;

	m_dataType = dataType;

	m_dataPtr = (void*) MGL_NEW u8[m_noComponents * (u8)m_dataType];
	ASSERT( m_dataPtr );
}

//-----------------------------------------------------------------------------

void	VertexIndexBuffer::ReleaseData()
{
	SAFE_DEL_ARRAY( m_dataPtr );
}

//-----------------------------------------------------------------------------

u32		VertexIndexBuffer::GetIndex(u32 index)
{
	switch( m_dataType )
	{
		case	eIDT_U_BYTE:
		{
			return (u32)((u8*)m_dataPtr)[index];
		}
		break;
		
		case	eIDT_U_SHORT:
		{
			return (u32)((u16*)m_dataPtr)[index];
		}
		break;
		
		case	eIDT_U_INT:
		{
			return (u32)((u32*)m_dataPtr)[index];
		}
		break;
		
		default:
			ASSERT( false && "Unknown data type!" );

	}
	return 0;
}

//-----------------------------------------------------------------------------

GLenum	VertexIndexBuffer::GetGLComponentType()
{
	switch( m_dataType )
	{
		case	eIDT_U_BYTE:
		{
			return GL_UNSIGNED_BYTE;
		}
		break;
		
		case	eIDT_U_SHORT:
		{
			return GL_UNSIGNED_SHORT;
		}
		break;
		
		case	eIDT_U_INT:
		{
			return GL_UNSIGNED_INT;
		}
		break;
		
		default:
			ASSERT( false && "Unknown data type!" );

	}
	return 0;
}

//-----------------------------------------------------------------------------

void	VertexIndexBuffer::calculateRange()
{
	ASSERT( m_dataPtr );
	u32 x;
	for( u32 i = 0; i < m_noComponents; i++ )
	{
		x = GetIndex( i );
		if( x > m_rangeMax )
		{
			m_rangeMax = x;
		}
		if( x < m_rangeMin )
		{
			m_rangeMin = x;
		}
	}
}

//-----------------------------------------------------------------------------

u32		VertexIndexBuffer::GetRangeMin()
{
	if( !m_hasRange )
	{
		calculateRange();
	}
	return m_rangeMin;
}

//-----------------------------------------------------------------------------

u32		VertexIndexBuffer::GetRangeMax()
{
	if( !m_hasRange )
	{
		calculateRange();
	}
	return m_rangeMax;
}

//-----------------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
